package com.aos.erp.gov.ex.task;

import com.aos.erp.common.exception.BizException;
import com.aos.erp.common.utils.DateUtils;
import com.aos.erp.gov.ex.GovConstants;
import com.aos.erp.gov.ex.enums.TaskSyncType;
import com.aos.erp.gov.ex.enums.TicketStatus;
import com.aos.erp.gov.ex.model.GovExSyncTask;
import com.aos.erp.gov.ex.model.GovSchoolTicket;
import com.aos.erp.gov.ex.service.GovExSyncTaskService;
import com.aos.erp.gov.ex.service.GovSchoolTicketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
//@Component
public class SyncTaskTrigger {

    @Resource
    private GovSchoolTicketService ticketService;
    @Resource
    private GovExSyncTaskService taskService;
    @Resource
    private SyncExecuteCenterAdapter centerAdapter;


    //1分钟检查一次
    @Scheduled(cron = "0 0/1 * * * *")
    public void keepLive() {
        //循环查询10条，进行处理
        Calendar calendar = Calendar.getInstance();
        //检查2分钟前的数据
        calendar.add(Calendar.MINUTE, -2);
        Date minDate = calendar.getTime();
        List<GovSchoolTicket> list = null;
        do {
            list = ticketService.getTopNeedRefresh(minDate);
            for (GovSchoolTicket ticket : list) {
                SyncExecuteCenter center = centerAdapter.matchCenter(ticket);
                if (center != null) {
                    try {
                        center.keepLive(ticket);
                        ticketService.updateSuccessStatus(ticket.getId(), Calendar.getInstance().getTime());
                    } catch (BizException e) {
                        log.error(e.getMessage(), e);
                        if (e.getCode() == GovConstants.NEED_LOGIN) {
                            //重定向了，说明过期了
                            ticketService.updateTimeOutStatus(ticket.getId(), Calendar.getInstance().getTime());
                        }
                    }
                }
            }
        } while (list.size() > 0);
    }


    /**
     * 从122 同步约考数据
     * 驾校+科目+场地，一个驾校，一天跑一次即可。
     */
    @Scheduled(cron = "0 0/15 * * * *")
    public void queryYK() {
        //循环查询10条，进行处理
        Calendar calendar = Calendar.getInstance();
        //检查1天前的数据
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        Date minDate = calendar.getTime();
        List<GovExSyncTask> list = null;
        do {
            list = taskService.getTopNeedSync(minDate, TaskSyncType.yk);
            taskExecute(list, TaskSyncType.yk);
        } while (list.size() > 0);
    }

    /**
     * 从122 同步考试成绩数据
     * 驾校+科目+场地，一个驾校，一天跑一次即可。
     */
    @Scheduled(cron = "0 0/15 * * * *")
    public void queryCj() {
        //循环查询10条，进行处理
        Calendar calendar = Calendar.getInstance();
        //检查1天前的数据
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        Date minDate = calendar.getTime();
        List<GovExSyncTask> list = null;

        do {
            list = taskService.getTopNeedSync(minDate, TaskSyncType.cj);
            taskExecute(list, TaskSyncType.cj);
        } while (list.size() > 0);
    }

    /**
     * 从122 同步预录入结果
     * 驾校+科目+场地，一个驾校，一天跑一次即可。
     */
    @Scheduled(cron = "0 0/15 * * * *")
    public void queryYlr() {
        //循环查询10条，进行处理
        Calendar calendar = Calendar.getInstance();
        //检查1天前的数据
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        Date minDate = calendar.getTime();
        List<GovExSyncTask> list = null;

        do {
            list = taskService.getTopNeedSync(minDate, TaskSyncType.ylr);
            taskExecute(list, TaskSyncType.ylr);
        } while (list.size() > 0);
    }

    private void taskExecute(List<GovExSyncTask> list, TaskSyncType type) {
        for (GovExSyncTask task : list) {
            GovSchoolTicket ticket = ticketService.getById(task.getTicketId());
            SyncExecuteCenter center = centerAdapter.matchCenter(ticket);
            if (center != null && ticket.getStatus() == TicketStatus.work) {
                //标记开始处理
                taskService.updateLastStartTime(task.getId(), Calendar.getInstance().getTime());
                int num = 0;
                try {
                    if (type == TaskSyncType.yk) {
                        num = center.syncYK(ticket, task);
                    } else if (type == TaskSyncType.cj) {
                        num = center.syncCJ(ticket, task);
                    } else if (type == TaskSyncType.ylr) {
                        num = center.syncYLR(ticket, task);
                    }
                } catch (BizException e) {
                    if (e.getCode() == GovConstants.NEED_LOGIN) {
                        //重定向了，说明过期了
                        ticketService.updateTimeOutStatus(ticket.getId(), Calendar.getInstance().getTime());
                    }
                }
                //标记结束
                taskService.updateLastEndTime(task.getId(), Calendar.getInstance().getTime(), num);
            } else {
                //延迟处理
                log.info(task.getAccount() + " 登录过期，无法处理预考查询任务，延期20分钟再做处理");
                taskService.updateLastStartTime(task.getId(), DateUtils.add(task.getLastStartTime(), Calendar.MINUTE, 20));
            }
        }
    }
}
